package com.czmh.etc.onlinepubsys.utils;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.czmh.etc.onlinepubsys.constants.GlobalStatusCode;

/**
 * 
 * @描述：
 * @author： Seven.
 * @创建日期：Jun 8, 2019 2:09:55 AM.
 * @版本：1.0.0
 */
public class RequestUtil {
	private static Logger logger = LoggerFactory.getLogger(RequestUtil.class);
	private static String UNKNOWN = "unknown";
	private static String LOCAL = "0:0:0:0:0:0:0:1";
	
	/**
	 * @param request
	 *            request
	 * @throws UnsupportedEncodingException
	 */
	public static void setCharacterEncoding(HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
	}

	/**
	 * @param request
	 * @param paramName
	 *            参数名称
	 * @return 从request获取参数对应字符串值
	 */
	public static String getString(HttpServletRequest request, String paramName) {
		String value = request.getParameter(paramName);
		return value != null ? value : "";
	}

	/**
	 * @param request
	 * @param paramName
	 *            参数名称
	 * @return 从request获取属性对应字符串值
	 */
	public static String getStrAtt(HttpServletRequest request, String paramName) {
		String value = (String) request.getAttribute(paramName);
		return value != null ? value : "";
	}

	/**
	 * @param request
	 * @param paramName
	 *            参数名称
	 * @return 从request获取参数对应数组值
	 */
	public static String[] getArray(HttpServletRequest request, String paramName) {
		return request.getParameterValues(paramName);
	}

	/**
	 * @param request
	 * @param paramName
	 *            参数名称
	 * @return 从request获取参数对应Byte值
	 */
	public static byte getByte(HttpServletRequest request, String paramName) {
		String value = request.getParameter(paramName);
		if (value == null || value.length() == 0){
			return 0;
		} else {
			return Byte.parseByte(value);
		}
	}

	/**
	 * @param request
	 * @param paramName
	 *            参数名称
	 * @return 从request获取参数对应整型值
	 */
	public static int getInt(HttpServletRequest request, String paramName) {
		String value = request.getParameter(paramName);
		if (value == null || value.length() == 0) {
            return 0;
        } else {
			try {
				return Integer.parseInt(value);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				return 0;
			}
		}
	}

	/**
	 * @param request
	 * @param paramName
	 *            参数名称
	 * @return 从request获取参数对应整型值
	 */
	public static int getIntAtt(HttpServletRequest request, String paramName) {
		String value = request.getAttribute(paramName).toString();
		if (value == null || value.length() == 0) {
            return 0;
        } else {
			try {
				return Integer.parseInt(value);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				return 0;
			}
		}
	}

	/**
	 * @param request
	 * @param paramName
	 *            参数名称
	 * @return 从request获取参数对应长整型值
	 */
	public static long getLong(HttpServletRequest request, String paramName) {
		String value = request.getParameter(paramName);
		if (value == null || value.length() == 0) {
            return 0L;
        } else {
			try {
				return Long.parseLong(value);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				return 0L;
			}
		}

	}

	/**
	 * @param request
	 * @param paramName
	 *            参数名称
	 * @return 从request获取参数对应短整型值
	 */
	public static short getShort(HttpServletRequest request, String paramName) {
		String value = request.getParameter(paramName);
		if (value == null || value.length() == 0){
			return 0;
		} else {
			return Short.parseShort(value);
		}
	}

	/**
	 * @param request
	 * @param paramName
	 *            参数名称
	 * @return 从request获取参数对应布尔值
	 */
	public static boolean getBoolean(HttpServletRequest request, String paramName) {
		String value = request.getParameter(paramName);
		if (value == null || value.length() == 0) {
			return false;
		} else {
			return Boolean.valueOf(value).booleanValue();
		}
	}
	
	/**
	 * 获取请求ip地址
	 * @param request
	 * @return
	 */
	public static String getRemoteIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (LOCAL.equals(ip)) {
			ip = "本地";
		}
		if (ip.split(",").length > 1) {
			ip = ip.split(",")[0];
		}
		return ip;
	}
	
	/**
	 * 获取请求头中的accesstoken
	 * 
	 * @param request      请求对象
	 * @return
	 * @throws Exception 
	 */
	public static String getAccessToken(HttpServletRequest request) throws Exception {
		// 从cookie中获取用户id和访问票据,要求前端在请求接口时需要将sa_id和access_token携带在cookie中
		String accessToken = "";
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
			    switch(cookie.getName()){
			        case GlobalStatusCode.ADMIN_ACCESSTOKEN : 
			        	accessToken = cookie.getValue();
			        	break;
			        default:
			            break;
			    }
			}
		}
		return accessToken;
	}
	
	/**
	 * 获取请求头信息集合
	 * 
	 * @param request        
	 * @return
	 * @throws Exception
	 */
    public static Map<String, String> getHeaders(HttpServletRequest request) throws Exception {
        Map<String, String> headers = new HashMap<String, String>();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                headers.put(name, values);
            }
            logger.info("header:{}", headers);
        }
        return headers;
    }
    
    /**
     * 获取指定名称的请求头信息
     * 
     * @param request       请求     
     * @param header        请求名称     
     * @return
     * @throws Exception
     */
    public static String getHeader(HttpServletRequest request, String header) throws Exception {
        Map<String, String> headers = new HashMap<String, String>();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                headers.put(name, values);
            }
            logger.info("header:{}", headers);
        }
        return headers.get(header);
    }
}
